package com.bawei.lib_storage.database

import com.bawei.lib_storage.database.entity.HistoryVideoEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

object HistoryManager {
    
    /**
     * 添加观看历史
     */
    suspend fun addHistory(
        videoId: Int,
        title: String,
        description: String,
        coverUrl: String,
        videoUrl: String,
        userId: String,
        watchDuration: Long = 0
    ): Boolean = withContext(Dispatchers.IO) {
        try {
            // 检查是否已存在历史记录
            val existingHistory = DBUtils.getDB().historyVideoDao().getByVideoIdAndUserId(videoId, userId)
            
            if (existingHistory != null) {
                // 如果已存在，更新观看时间和时长
                val updatedHistory = existingHistory.copy(
                    watchTime = System.currentTimeMillis(),
                    watchDuration = watchDuration
                )
                DBUtils.getDB().historyVideoDao().update(updatedHistory)
            } else {
                // 如果不存在，创建新的历史记录
                val historyVideo = HistoryVideoEntity(
                    videoId = videoId,
                    title = title,
                    description = description,
                    coverUrl = coverUrl,
                    videoUrl = videoUrl,
                    userId = userId,
                    watchDuration = watchDuration
                )
                DBUtils.getDB().historyVideoDao().insert(historyVideo)
            }
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }
    
    /**
     * 删除历史记录
     */
    suspend fun removeHistory(videoId: Int, userId: String): Boolean = withContext(Dispatchers.IO) {
        try {
            DBUtils.getDB().historyVideoDao().deleteByVideoIdAndUserId(videoId, userId)
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }
    
    /**
     * 检查是否在历史记录中
     */
    suspend fun isInHistory(videoId: Int, userId: String): Boolean = withContext(Dispatchers.IO) {
        try {
            DBUtils.getDB().historyVideoDao().isInHistory(videoId, userId)
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }
    
    /**
     * 获取用户的所有历史记录
     */
    suspend fun getAllHistory(userId: String): List<HistoryVideoEntity> = withContext(Dispatchers.IO) {
        try {
            android.util.Log.d("HistoryManager", "Getting all history for userId: $userId")
            val history = DBUtils.getDB().historyVideoDao().getAllByUserId(userId)
            android.util.Log.d("HistoryManager", "Found ${history.size} history records")
            history
        } catch (e: Exception) {
            e.printStackTrace()
            android.util.Log.e("HistoryManager", "Error getting history", e)
            emptyList()
        }
    }
    
    /**
     * 清空用户的所有历史记录
     */
    suspend fun clearAllHistory(userId: String): Boolean = withContext(Dispatchers.IO) {
        try {
            DBUtils.getDB().historyVideoDao().deleteAllByUserId(userId)
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }
    
    /**
     * 删除旧的历史记录（保留最近30天）
     */
    suspend fun cleanOldHistory(userId: String): Boolean = withContext(Dispatchers.IO) {
        try {
            val thirtyDaysAgo = System.currentTimeMillis() - (30 * 24 * 60 * 60 * 1000L)
            DBUtils.getDB().historyVideoDao().deleteOldHistory(userId, thirtyDaysAgo)
            true
        } catch (e: Exception) {
            e.printStackTrace()
            false
        }
    }
} 